package com.fuping;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.TimeZone;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class AutoSign {

	private static final String LIKE_INDEX_URL = "http://tieba.baidu.com/f/like/mylike?v=" + System.currentTimeMillis();

	private static final String TIEBA_PRE_URL = "http://tieba.baidu.com/f?ie=utf-8&fr=search&kw=";

	private static String cookie;
	static {
		cookie = readCookie();
	}

	public static void main(String[] args) {
		String cookie = readCookie();
		Document doc1 = getDoc(LIKE_INDEX_URL, cookie);
		// System.out.println(cookie);
		int maxIndex = getMaxPageIndex(doc1);
		List<TBInfo> lt = getTieBas(maxIndex);
		StringBuffer sb = new StringBuffer();
		int count = 0;
		SimpleDateFormat ymdsdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		ymdsdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		long startTime = System.currentTimeMillis();
		sb.append(
				"<span style=\"color: rgb(255, 0, 0);\"><b>" + ymdsdf.format(new Date()) + "签到结果:</b></span><br><br>");
		sb.append(sdf.format(new Date(startTime)) + "开始签到：");
		sb.append("<br>*************************************************************************<br>");
		for (TBInfo tbInfo : lt) {

			String result = sign(tbInfo.getTitle(), getTbs(tbInfo.getTitle()));
			System.out.println(result);
			sb.append(result + "<br>");
		}
		long endtTime = System.currentTimeMillis();
		sb.append("************************************************************************<br>");
		sb.append("<br>" + sdf.format(new Date(endtTime)) + "结束签到,耗时" + (endtTime - startTime) + "毫秒<br>");
		while (!SendMail(sb.toString())) {

			if (count >= 10) {
				break;
			}
			SendMail(sb.toString());
			count++;
		}
	}

	public static String readCookie() {
		File f = new File("baidu.cookie");
		FileReader fr;
		BufferedReader br;
		String cookie = null;
		try {
			fr = new FileReader(f);
			br = new BufferedReader(fr);
			while (br.read() != -1) {
				cookie = br.readLine();
			}
			br.close();
			fr.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cookie;
	}
	public static Mail loadProperties() {

		Mail mail = null;
		InputStream in = ClassLoader
				.getSystemResourceAsStream("config.properties");
		Properties p = new Properties();
		try {
			p.load(in);
			Enumeration<Object> e = p.keys();
			if (e.hasMoreElements()) {
				mail = new Mail();
				//String key = e.nextElement().toString();
				//map.put(key, p.getProperty(key));
				mail.setMailFrom(p.getProperty("mailfrom"));
				mail.setMailPwd(p.getProperty("mailpwd"));
				mail.setMailTo(p.getProperty("mailto"));
				mail.setSmtp(p.getProperty("smtp"));
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			mail = null;
		}
		return mail;

	}
	private static boolean SendMail(String content) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		String subject = sdf.format(new Date()) + "签到结果";
		//return MailSend.send(Util.SMTP, Util.MailFrom, Util.MailTo, subject, content, Util.MailUserName, Util.MailPassWord);
		Mail mail = loadProperties();
		//return MailSend.send(Util.SMTP, Util.MailFrom, Util.MailTo, subject, content, Util.MailUserName, Util.MailPassWord);
		return MailSend.send(mail, subject, content);
	}

	private static String sign(String tbName, String tbs) {
		Document doc = null;

		String result = null;
		String tbName2 = null;
		try {
			tbName2 = URLEncoder.encode(tbName, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			doc = Jsoup
					.connect("http://tieba.baidu.com/mo/q/sign?tbs=" + tbs + "&kw=" + tbName2 + "&is_like=1&fid=6570")
					.header("Accept", "text/*").header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
					.cookie("cookie", cookie).timeout(10000).ignoreContentType(true)
					.header("X-Requested-With", "XMLHttpRequest")
					.userAgent(
							"Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/47.0.2526.70 Mobile/13C71 Safari/601.1.46")
					.get();
			JSONObject json = new JSONObject(doc.text());

			result = tbName + "--------->" + Result.getName(Integer.parseInt(json.get("no").toString()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	private static String getTbs(String tbName) {
		String tbs = null;
		Document doc = getDoc(TIEBA_PRE_URL + tbName, cookie);
		Elements ss = doc.getElementsByTag("script");
		for (Element element : ss) {
			if (element.outerHtml().contains("PageData.user") && !element.outerHtml().contains("Bigpipe")) {
				ScriptEngineManager sem = new ScriptEngineManager();
				ScriptEngine se = sem.getEngineByName("js");
				StringBuffer sb = new StringBuffer();
				sb.append(element.html());
				sb.append("var mytbs = PageData.tbs;");

				try {
					se.eval(sb.toString());
				} catch (ScriptException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Object obj = se.get("mytbs");// 获取js中对象
				tbs = (String) obj;
			}

		}
		return tbs;
	}

	private static List<TBInfo> getTieBas(int maxPageIndex) {

		List<TBInfo> lt = new ArrayList<TBInfo>();
		Document doc = null;
		for (int i = 1; i <= maxPageIndex; i++) {
			doc = getDoc(LIKE_INDEX_URL + "&pn=" + i, cookie);
			Element alltbs = doc.select("div.forum_table").first();
			Elements tbs = alltbs.select("tr");

			for (int j = 1; j < tbs.size(); j++) {
				Element element = tbs.get(j);
				TBInfo tb = new TBInfo();
				tb.setUrl(element.select("a").attr("href"));
				tb.setTitle(element.select("a").attr("title"));
				tb.setBadgeTitle(element.select("a").select("div.like_badge_title").text());
				tb.setExp(Integer.parseInt(element.select("a.cur_exp").text()));

				tb.setBadgeLv(Integer.parseInt(element.select("a").select("div.like_badge_lv").text()));

				lt.add(tb);
			}
		}
		return lt;
	}

	private static int getMaxPageIndex(Document doc) {

		int pageCount = -1;
		Element page = doc.select("div.pagination").first();
		String maxPageIndexUrl = null;
		Elements pages = page.select("a");
		for (Element element : pages) {
			if (element.text().equals("尾页")) {
				maxPageIndexUrl = element.absUrl("href");
			}
		}
		pageCount = Integer.parseInt(maxPageIndexUrl.split("&pn=")[1]);
		return pageCount;
	}

	private static Document getDoc(String url, String cookie) {

		Document doc = null;
		try {
			doc = Jsoup.connect(url).header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
					.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3").cookie("cookie", cookie)
					.timeout(10000)
					.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
					// .referrer("http://tieba.baidu.com/i/28870963/forum")
					.get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return doc;
	}

}
